﻿using System.Windows.Forms;
using System.Linq;
using System.Linq.Expressions;
using System;

namespace nToDo
{
    public partial class AddNewTaskUI : Form
    {
        public event EventHandler onEventAdded;
        private bool editMode = false;
        private string taskId = string.Empty;
        public AddNewTaskUI(DateTime currentDate)
        {
            InitializeComponent();
            this.priorityCombo.SelectedIndex = 1;
            this.dueDatepicker.Value = currentDate;
        }

        public AddNewTaskUI(string TaskId)
        {
            InitializeComponent();
            this.editMode = true;
            this.taskId = TaskId;
            this.Text = "Edit Task";
            this.SaveButton.Text = "Edit Task";
            this.FillUI(TaskId);
        }

        private void FillUI(string TaskId)
        {
            Task t = DataAccess.GetInstance().GetTask(TaskId);
            this.dueDatepicker.Value = t.DueDate;
            this.notesText.Text = t.Notes;
            this.priorityCombo.SelectedIndex = t.Priority;
        }

        private void SaveButton_Click(object sender, System.EventArgs e)
        {
            if (this.priorityCombo.SelectedIndex != -1 && this.notesText.Text.Trim().Length >= 1)
            {
                if (this.editMode)
                {
                    DataAccess.GetInstance().RemoveTask(this.taskId);
                }

                Task t = new Task()
                {
                    DueDate = this.dueDatepicker.Value,
                    IsDone = false,
                    Notes = this.notesText.Text.Trim(),
                    Priority = this.priorityCombo.SelectedIndex
                };
                DataAccess.GetInstance().AddTask(t);
                this.notesText.Text = string.Empty;
                this.priorityCombo.SelectedIndex = 1;
                if (this.onEventAdded != null)
                {
                    this.onEventAdded(this, EventArgs.Empty);
                }
                if (this.editMode)
                {
                    this.Close();
                }
            }
        }

        private void UICancelButton_Click(object sender, System.EventArgs e)
        {
            this.Close();
        }

        private void toDayButton_Click(object sender, EventArgs e)
        {
            this.dueDatepicker.Value = DateTime.Now;
        }
    }
}
